<template>
  <div class="vehicle-entry-exit-review bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">车辆出入审核</h2>

    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchApplications" @reset="resetSearch" />
    </div>
    <!--  -->
    <div class="mb-4 space-x-2">
      <el-button @click="exportData(applications, '车辆审核', selectedIds)">导出</el-button>
    </div>
    <!-- Data Table -->

    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedApplications" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">
        <el-table-column prop="DRIVER_NAME" label="驾驶员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="LICENSE_PLATE" label="车牌号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="TRANSPORT_COMPANY" label="前往企业" header-align="center" align="center"></el-table-column>
        <el-table-column prop="TRANS_STATUS" label="运货状态" header-align="center" align="center"></el-table-column>
        <el-table-column prop="IN_AT" label="预计入园时间" header-align="center" align="center">
          <template #default="scope">
            <div>{{ dayjs(scope.row.IN_AT).format('YYYY-MM-DD HH:mm:ss') }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="AUDITOR" label="审核人" header-align="center" align="center"></el-table-column>
        <el-table-column prop="AU_STATUS" label="审核状态" header-align="center" align="center">
          <template #default="scope">
            <div :class="getStatusClass(scope.row.AU_STATUS)">
              {{ scope.row.AU_STATUS }}
            </div>
          </template>

        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button v-if="scope.row.AU_STATUS == '待审核'" type="primary" size="small"
              @click="reviewApplication(scope.row)" link>审核</el-button>
            <el-button v-else type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button>
          </template>
        </el-table-column>

        <!-- 
        <el-table-column prop="application_time" label="提交时间" header-align="center" align="center">
          <template #default="scope">
            <div>{{ dayjs(scope.row.application_time).format('YYYY-MM-DD HH:mm:ss') }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="application_status" label="申请状态" header-align="center" align="center">
          <template #default="scope">
            <div :class="getStatusClass(scope.row.application_status)">
              {{ scope.row.application_status }}
            </div>
          </template>

        </el-table-column> -->

      </el-table>
    </div>
    <!-- Pagination -->
    <Pagination v-if="applications.length" :tableData="applications" @alltabledata="alltabledata" />
    <!-- Review Dialog -->
    <el-dialog class="dialog-from" v-model="isReviewDialogOpen" title="审核申请" width="650" destroy-on-close align-center>
      <form>

        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>基本信息</span>
        </div>
        <div class="grid grid-cols-3 gap-4">
          <div><strong>系统单号：</strong>{{ reviewForm.ID }}</div>
          <div><strong>车牌号码：</strong>{{ reviewForm.LICENSE_PLATE }}</div>
          <div><strong>车辆类型：</strong>{{ reviewForm.VEHICLE_TYPE }}</div>
          <div><strong>车牌颜色：</strong>{{ reviewForm.LICENSE_PLATE_COLOR }}</div>
          <div><strong>所属运输企业编码：</strong>{{ reviewForm.COMPANY_CODE }}</div>

          <div><strong>货运状态：</strong>{{ reviewForm.TRANS_STATUS }}</div>
          <div><strong>前往企业：</strong>{{ reviewForm.transport_company }}</div>
          <div><strong>预计入园时间：</strong>{{ formatDateTime(reviewForm.in_at) }}</div>
          <div><strong>预计出园时间：</strong>{{ formatDateTime(reviewForm.exit_at) }}</div>

        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>驾驶员信息</span>
        </div>
        <div class="grid grid-cols-3 gap-4">
          <div><strong>驾驶员姓名：</strong>{{ reviewForm.DRIVER_NAME }}</div>
          <div><strong>证件号码：</strong>{{ reviewForm.DRIVER_ID_CARD }}</div>
          <div><strong>联系方式：</strong>{{ reviewForm.phone_number }}</div>
          <div><strong>行驶证：</strong>{{ reviewForm.DRIVING_LICENSE }}</div>
          <div><strong>有效期起：</strong>{{ formatDateTime(reviewForm.LEN_START_DATE) }}</div>
          <div><strong>有效期止：</strong>{{ formatDateTime(reviewForm.LEN_END_DATE) }}</div>
          <div><strong>是否有效：</strong>{{ reviewForm.WHETHER_LEN }}</div>
        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>申请信息</span>
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>

            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">授权类型：</label>
              <el-select v-model="reservationreviewForm.STATUS" class="set-select" placeholder="请选择">
                <el-option label="长期" value="长期" />
                <el-option label="临时" value="临时" />
              </el-select>
            </div>
          </div>
          <div>
            <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">到期日期：</label>
            <input type="datetime-local" v-model="reservationreviewForm.END_TIME" class="input" />
          </div>
        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>其他信息</span>
        </div>
        <div><strong>备注：</strong>{{ reviewForm.stamp }}</div>
        <div class="mt-6 flex justify-end space-x-2">
          <el-button type="primary" @click.prevent="submitReview('通过')">通过</el-button>
          <el-button type="primary" @click.prevent='submitReview("未通过")'>未通过</el-button>
          <el-button @click="closeReviewDialog">取消</el-button>
        </div>
      </form>
    </el-dialog>
    <!-- View Details Dialog -->
    <el-dialog class="dialog-from" v-model="isViewDialogOpen" title="查看申请详情" width="650" destroy-on-close align-center>



      <div class="tablename">
        <div
          style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
        </div>
        <span>基本信息</span>
      </div>
      <div class="grid grid-cols-3 gap-4">
        <div><strong>系统单号：</strong>{{ viewingItem.ID }}</div>
        <div><strong>车牌号码：</strong>{{ viewingItem.LICENSE_PLATE }}</div>
        <div><strong>车辆类型：</strong>{{ viewingItem.VEHICLE_TYPE }}</div>
        <div><strong>车牌颜色：</strong>{{ viewingItem.LICENSE_PLATE_COLOR }}</div>
        <div><strong>所属运输企业编码：</strong>{{ viewingItem.COMPANY_CODE }}</div>
        <div><strong>货运状态：</strong>{{ viewingItem.TRANS_STATUS }}</div>
        <div><strong>前往企业：</strong>{{ viewingItem.TRANSPORT_COMPANY }}</div>
        <div><strong>预计入园时间：</strong>{{ formatDateTime(viewingItem.IN_AT) }}</div>
        <!-- <div><strong>预计出园时间：</strong>{{ formatDateTime(viewingItem.exit_at) }}</div> -->
      </div>
      <div class="tablename">
        <div
          style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
        </div>
        <span>驾驶员信息</span>
      </div>
      <div class="grid grid-cols-3 gap-4">
        <div><strong>驾驶员姓名：</strong>{{ viewingItem.DRIVER_NAME }}</div>
        <div><strong>证件号码：</strong>{{ viewingItem.DRIVER_ID_CARD }}</div>
        <div><strong>联系方式：</strong>{{ viewingItem.PHONE_NUMBER }}</div>
        <div><strong>行驶证：</strong>{{ viewingItem.DRIVING_LICENSE }}</div>
        <div><strong>有效期起：</strong>{{ formatDateTime(viewingItem.LEN_START_DATE) }}</div>
        <div><strong>有效期止：</strong>{{ formatDateTime(viewingItem.LEN_END_DATE) }}</div>
        <div><strong>是否有效：</strong>{{ viewingItem.WHETHER_LEN }}</div>
      </div>
      <div class="tablename">
        <div
          style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
        </div>
        <span>其他信息</span>
      </div>
      <div><strong>备注：</strong>{{ viewingItem.STAMP }}</div>
      <div class="mt-6 flex justify-end space-x-2">
        <el-button @click="closeViewDialog">关闭</el-button>
      </div>


    </el-dialog>


  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import axios from 'axios'

import { dayjs } from "element-plus"
const { proxy } = getCurrentInstance()
const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/vehicle-entry-exit'
})
import { exportData } from '#/utils/exportfile.js'
const loading = ref(false)
const displayedPlanData = ref([])


const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const rowKey = (row) => row.ID // 设置行的唯一标识
const search = ref({
  LICENSE_PLATE: '',
  DRIVER_NAME: '',
  VEHICLE_TYPE: '',
  AU_STATUS: '',
})
const formItems = ref([
  {
    label: '车牌号码：',
    model: 'LICENSE_PLATE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '驾驶员姓名：',
    model: 'DRIVER_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  // {
  //   label: '车辆类型：',
  //   model: 'VEHICLE_TYPE',
  //   type: 'select',
  //   placeholder: '请选择',
  //   options: [
  //     { label: '普货车', value: '普货车' },
  //     { label: '危化品运输车', value: '危化品运输车' },
  //     { label: '小型车', value: '小型车' },
  //     { label: '应急车辆', value: '应急车辆' },
  //   ],
  // },
  {
    label: '状态：',
    model: 'AU_STATUS',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '待审核', value: '待审核' },
      { label: '未通过', value: '未通过' },
      { label: '通过', value: '通过' },
    ],
  },
])
const reservationreviewForm = ref({
  ID: '',
  STATUS: '',
  END_TIME: '',
  AU_STATUS: '',
  APPLICATION_STATUS: '',
  PLATE_NUMBER: '',
  DRIVER_NAME: '',
  VEHICLE_TYPE: '',
  DRIVER_ID_CARD: '',
})
const applications = ref([])

const isReviewDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const reviewForm = ref({
  STATUS: '',
  END_TIME: ''
})
const viewingItem = ref(null)

const displayedApplications = ref([])
const alltabledata = (data) => {
  displayedApplications.value = data

}

const searchApplications = async () => {
  displayedApplications.value = []

  try {
    const response = await axios.get(`${apiBaseUrl.value}/application/review/search`, { params: search.value })
    applications.value = response.data
  } catch (error) {
    console.error('搜索申请失败:', error)
    alert('搜索申请失败: ' + (error.response?.data?.message || error.message))
  }
}

const resetSearch = () => {

  search.value = {
    LICENSE_PLATE: '',
    DRIVER_NAME: '',
    VEHICLE_TYPE: '',
    AU_STATUS: '',
  }
  searchApplications()
}

const reviewApplication = (application) => {
  reviewForm.value = {
    ...application
  }
  reservationreviewForm.value.ID = application.ID
  isReviewDialogOpen.value = true
}

const closeReviewDialog = () => {
  isReviewDialogOpen.value = false
}

const submitReview = async (data) => {
  reservationreviewForm.value.AU_STATUS = data
  reservationreviewForm.value.APPLICATION_STATUS = data == '通过' ? '通过' : '未通过'
  reservationreviewForm.value.PLATE_NUMBER = reviewForm.value.LICENSE_PLATE
  reservationreviewForm.value.DRIVER_NAME = reviewForm.value.DRIVER_NAME
  reservationreviewForm.value.VEHICLE_TYPE = reviewForm.value.VEHICLE_TYPE
  reservationreviewForm.value.DRIVER_ID_CARD = reviewForm.value.DRIVER_ID_CARD
  console.log(reservationreviewForm.value)
  try {
    await axios.post(`${apiBaseUrl.value}/application/${reservationreviewForm.value.ID}/review`, reservationreviewForm.value)
    alert('审核提交成功')
    // if (reviewForm.value.review_result === '通过') {

    //   await axios.post(`${proxy.$currentUrl}/vehicle-pass`, {
    //     LICENSE_PLATE: reviewForm.value.LICENSE_PLATE,
    //     VEHICLE_TYPE: reviewForm.value.VEHICLE_TYPE,
    //   })

    // }
    closeReviewDialog()
    await searchApplications()
  } catch (error) {
    console.error('审核提交失败:', error)
    alert('审核提交失败: ' + (error.response?.data?.message || error.message))
  }
}

const viewDetails = (item) => {
  viewingItem.value = item
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingItem.value = {}
}


const getStatusClass = (status) => {
  const classMap = {
    '待审核': 'bg-yellow-100 text-yellow-800',
    '通过': 'bg-green-100 text-green-800',
    '未通过': 'bg-red-100 text-red-800'
  }
  return `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${classMap[status] || ''}`
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

onMounted(() => {
  searchApplications()
})
</script>

<style scoped>
.input {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.tablename {
  display: flex;
  align-items: baseline;
  margin: 10px 0;
  font-weight: bold;
}
</style>
